<!--
 * @Author: zhangyang
 * @Date: 2022-05-31 10:39:02
 * @LastEditTime: 2022-06-01 09:23:23
 * @Description: 
-->
<script lang="ts" setup>
import useFormMode from '@/hooks/useFormMode';
import { NButton, NInput, NSpace, NSwitch, type SelectOption } from 'naive-ui';
import type { TableDataItem, TableHeadItemPro, UserItem, BaseQuery, RoleItem } from '@/typings';
import { addUserItem, changeUserItem, deleteUser, getUserList } from '@/api/user';
import { getRoleList } from '@/api/role';
import { setDialogCenter } from '@/layouts/components/hooks/useUser';

interface Form extends UserItem {};
const FORM_TEMP: Form = {
  id: 0,
  username: '',
  nickname: '',
  mobile: '',
  roleId: 1,
  status: 1,
  initPassword: ''
};
const {
  isAdd,
  isEdit,
  edit,
  del,
  sure,
  clear,
  form,
  formRef,
  // @ts-ignore
  validForm
} = useFormMode<Form>(FORM_TEMP, {
  // @ts-ignore
  addCbk: async () => {
    const res: boolean = await validForm();
    if (res) {
      const v = deepClone(form.value);
      clear();
      await addUserItem(v);
      window.$message.success('新增成功！');
    }
    return res;
  },
  // @ts-ignore
  modCbk: async () => {
    const res: boolean = await validForm();
    if (res) {
      const v = deepClone(form.value);
      clear();
      await changeUserItem(v);
      window.$message.success('修改成功！');
    }
    return res;
  },
  delCbk: async (row) => {
    await deleteUser(row.id.toString());
    window.$message.success('删除成功！');
    query.pageNum = 1;
  },
  cgEffect: () => getList()
});
const renderOperate = (row: TableDataItem<Form>) => {
  return h(NSpace, {}, {
    default: () => [
      h(
        NButton,
        { type: 'info', size: 'small', ghost: true, onClick: () => edit(row) },
        { default: () => '编辑' }
      ),
      h(
        NButton,
        { type: 'warning', size: 'small', ghost: true, onClick: async () => {
            let newPassword = '';
            window.$alert.warning({
              title: '修改密码',
              content: () => h(NInput, {
                placeholder: '请输入新密码',
                onChange: (e) => {
                  newPassword = e;
                }
              }),
              'negative-text': '取消',
              'positive-text': '确认',
              onPositiveClick: async () => {
                return new Promise(async (resolve) => {
                  try {
                    await changeUserItem({ id: row.id, newPassword });
                    resolve(true);
                  } catch (error) {
                    resolve(false);
                  }
                });
              }
            }).style = setDialogCenter();
          }
        },
        { default: () => '修改密码' }
      ),
      h(
        NButton,
        { type: 'error', size: 'small', ghost: true, onClick: () => del(row) },
        { default: () => '删除' }
      ),
    ]
  })
};
const tableHead: TableHeadItemPro<Form>[] = [
  { key: 'id', title: '用户ID' },
  { key: 'username', title: '用户名' },
  { key: 'mobile', title: '手机号' },
  { key: 'role_name', title: '角色名称' },
  { key: 'creator', title: '创建信息' },
  { key: 'status', title: '禁用/启用', render: (row) => h(NSwitch, {
      size: 'small', 
      checkedValue: 1,
      uncheckedValue: 0,
      value: row.status,
      onUpdateValue: async (status) => {
        await changeUserItem({ id: row.id, status });
        window.$message.success('修改成功！');
        getList();
      }
    })
  },
  { key: 'autoid', title: '操作', render: renderOperate, width: '320' }
];
interface Query extends BaseQuery {
  username: string;
  mobile: string;
  status: 0 | 1;
};
const query = reactive<Query>({
  pageNum: 1,
  pageSize: 50,
  total: 0,
  username: '',
  mobile: '',
  status: 1
});

const tableData = ref<TableDataItem[]>([]);
const roleList = ref<SelectOption[]>([]);
const getList = async () => {
  const { list: role_list } = await getRoleList({ noPagination: true });
  roleList.value = (role_list || []).map((item: RoleItem) => {
    return {
      label: item.desc,
      value: item.id
    };
  });

  const { list, pageNum, pageSize, total } = await getUserList(query);
  tableData.value = deepClone(list || []);
  query.pageNum = pageNum;
  query.pageSize = pageSize;
  query.total = total;
};

getList();
</script>

<route lang="yaml">
meta:
  title: 用户列表
  authPath: /system/user
</route>

<template>
  <div class="flex">
    <div class="m-2">
      <NInput v-model:value="query.username" placeholder="请输入用户名" />
    </div>
    <div class="m-2">
      <NInput v-model:value="query.mobile" placeholder="请输入手机号" />
    </div>
    <div class="m-2 w-50">
      <NSelect
        v-model:value="query.status"
        placeholder="请选择状态"
        clearable
        :options="[
          { label: '1-启用', value: 1 },
          { label: '0-禁用', value: 0 },
        ]"
      />
    </div>
    <div class="m-2">
      <NButton type="info" ghost @click="getList">搜索</NButton>
    </div>
    <div class="m-2">
      <NButton type="success" ghost @click="isAdd=true">添加用户</NButton>
    </div>
  </div>
  <div class="m-2">
    <YoungTablePro
      v-model:page="query.pageNum"
      v-model:limit="query.pageSize"
      :total="query.total"
      :table-data="tableData"
      :table-head="tableHead"
      @page-change="getList"
    />
  </div>
  <YoungDialog
    :is-add="isAdd"
    :is-edit="isEdit"
    @sure="sure"
    @clear="clear"
  >
    <template #body>
      <NForm
        ref="formRef"
        :model="form"
        label-placement="left"
        label-width="100"
      >
        <NFormItem
          label="用户名"
          path="username"
          :rule="[{ required: true, message: '请输用户名', trigger: 'blur' }]"
        >
          <NInput v-model:value="form.username" />
        </NFormItem>
        <NFormItem
          label="昵称"
          path="nickname"
          :rule="[{ required: true, message: '请输昵称(用于右上角展示)', trigger: 'blur' }]"
        >
          <NInput v-model:value="form.nickname" />
        </NFormItem>
        <NFormItem
          label="手机号"
          path="mobile"
          :rule="[{ required: true, message: '请输手机号', trigger: 'blur' }]"
        >
          <NInput v-model:value="form.mobile" />
        </NFormItem>
        <NFormItem
          label="角色"
        >
          <NSelect v-model:value="form.roleId" :options="roleList" />
        </NFormItem>
        <NFormItem
          v-if="isAdd"
          label="初始密码"
          path="initPassword"
          :rule="[{ required: true, message: '请输初始密码', trigger: 'blur' }]"
        >
          <NInput v-model:value="form.initPassword" />
        </NFormItem>
      </NForm>
    </template>
  </YoungDialog>
</template>